// #include <QGuiApplication>
// #include <QQmlApplicationEngine>
//
// int main(int argc, char *argv[])
// {
// #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
//     QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// #endif
//     QGuiApplication app(argc, argv);
//
//     QQmlApplicationEngine engine;
//     const QUrl url(QStringLiteral("qrc:/main.qml"));
//     QObject::connect(
//         &engine,
//         &QQmlApplicationEngine::objectCreated,
//         &app,
//         [url](QObject *obj, const QUrl &objUrl) {
//             if (!obj && url == objUrl)
//                 QCoreApplication::exit(-1);
//         },
//         Qt::QueuedConnection);
//     engine.load(url);
//
//     return app.exec();
// }
//


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QQmlError>
#include <QQmlComponent>

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    // 注册 GlobalState.qml 为单例
    qmlRegisterSingletonType(QUrl("qrc:/qml_src/Global/GlobalState.qml"),
                             "App.Global", 1, 0, "GlobalState");

    const QUrl url(QStringLiteral("qrc:/main.qml"));

    // 连接警告信号，打印 QML 错误和警告
    QObject::connect(&engine, &QQmlApplicationEngine::warnings,
                     [](const QList<QQmlError> &warnings) {
        for (const QQmlError &warning : warnings) {
            qWarning() << "QML Warning/Error:" << warning.toString();
        }
    });

    // 连接加载完成信号，检查是否加载成功
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app,
                     [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl) {
            qCritical() << "Failed to load QML file:" << objUrl.toString();
            QCoreApplication::exit(-1);
        }
    }, Qt::QueuedConnection);

    try {
        engine.load(url);
    } catch (const std::exception &ex) {
        qCritical() << "Exception caught while loading QML:" << ex.what();
        return -1;
    } catch (...) {
        qCritical() << "Unknown exception caught while loading QML.";
        return -1;
    }

    return app.exec();
}
